package cn.okcmd.base;

import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * create by caoqg on 2021/7/17
 * 功能说明: 测试unsafe 类
 */
@Slf4j
public class TestUnsafe {
    private byte varByte=11;
    private char varChar=12;
    private short varShort=13;
    private int varInt=14;
    private long varLong=15;
    private float varFloat=16;
    private double varDouble=17;
    private boolean varBoolean=true;

    private static Unsafe unsafe;

    private static long offsetVarByte;
    private static long offsetVarChar;
    private static long offsetVarBoolean;
    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(Unsafe.class);
            offsetVarByte = getOffset("varByte");
            offsetVarChar = getOffset("varChar");
            offsetVarBoolean = getOffset("varBoolean");
        } catch (Exception e) {
            throw new Error("start err");
        }
    }

    public static long getOffset(String fieldName) throws NoSuchFieldException {
        Field field = TestUnsafe.class.getDeclaredField(fieldName);
        long offset = unsafe.objectFieldOffset(field);
        return offset;
    }


    public static void main(String[] args) {
        System.out.println(unsafe);
        TestUnsafe testUnsafe = new TestUnsafe();

        byte byte1 = testUnsafe.varByte;
        unsafe.putByte(testUnsafe,offsetVarByte,(byte) 21);
        byte byte2 = testUnsafe.varByte;
        log.info("byte before:{},after:{}",byte1,byte2);

        boolean bool1 = testUnsafe.varBoolean;
        unsafe.putBoolean(testUnsafe, offsetVarBoolean, false);
        boolean bool2 = testUnsafe.varBoolean;
        log.info("bool before:{},after:{}",bool1,bool2);

    }

}
